package com.coocaa.ops.admin.v1.poster.service.impl;


import com.coocaa.ops.admin.base.language.CommonLanguageProperties;
import com.coocaa.ops.admin.v1.audit.AuditUtil;
import com.coocaa.ops.admin.v1.audit.model.ExecutionTaskModel;
import com.coocaa.ops.admin.v1.audit.service.impl.AuditTaskServiceImpl;
import com.coocaa.ops.admin.v1.poster.biz.impl.GlobalPictureBizImpl;
import com.coocaa.ops.admin.v1.poster.convert.PosterSaveConverter;
import com.coocaa.ops.admin.v1.poster.service.IGlobalPictureUpdateProvider;
import com.coocaa.ops.admin.v1.poster.service.IGlobalPictureUpdateService;
import com.coocaa.ops.admin.v1.poster.validator.PosterValidator;
import com.coocaa.ops.common.core.base.enums.ResourceTypeEnum;
import com.coocaa.ops.common.core.base.model.R;
import com.coocaa.ops.common.core.base.model.SimpleSysUserInfo;
import com.coocaa.ops.common.core.base.mybatis.UpdateTemplate;
import com.coocaa.ops.common.core.biz.audit.entity.AuditTaskInfoEntity;
import com.coocaa.ops.common.core.biz.auth.entity.SysUserEntity;
import com.coocaa.ops.common.core.biz.poster.entity.GlobalPictureEntity;
import com.coocaa.ops.common.tool.base.InstanceUtil;
import com.coocaa.ops.common.tool.date.DateUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author bjh
 * @description 素材图片表-更新service接口实现
 * @date 2020-06-13 10:50:35
 */
@Service
public class GlobalPictureUpdateServiceImpl implements IGlobalPictureUpdateService {
    @Autowired
    private IGlobalPictureUpdateProvider thisUpdateProvider;
    @Autowired
    private GlobalPictureBizImpl posterBiz;
    @Autowired
    private AuditTaskServiceImpl auditTaskService;
    private static CommonLanguageProperties commonLanguageProperties;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveBatch(List<GlobalPictureEntity> list, SysUserEntity user) {
        if (CollectionUtils.isNotEmpty(list)) {
            if (list.size() == 1 && list.get(0).getId() != null) {
                // 修改
                save(list.get(0), user);
            } else {
                //批量新增
                addBatchPicture(list, user);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(GlobalPictureEntity entity, SysUserEntity user) {
        thisUpdateProvider.save(entity, user.getId());
        AuditTaskInfoEntity taskInfoEntity = AuditUtil.openTask(entity.getPictureName(), entity.getId(), null, ResourceTypeEnum.POSTER.toString(), null,
                user, 1);
//        if (SystemProperties.SystemConstants.ENABLE_SEND_EMAIL) {
//            //发送邮件通知审核人
//            sendEmailService.sentEmailForPicture(entity, user, taskInfoEntity);
//        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void batchAudit(String pictureIdsStr, SysUserEntity user, Integer auditFlag, String auditDesc) {
        if (StringUtils.isNotBlank(pictureIdsStr)) {
            String[] pictureIds = pictureIdsStr.split(",");
            for (String pictureId : pictureIds) {
                //审核素材
                ExecutionTaskModel executionTaskModel = ExecutionTaskModel.getExecutionTaskModel(Integer.valueOf(pictureId), 0, ResourceTypeEnum.POSTER.toString(), auditFlag);
                executionTaskModel.setAuditDesc(auditDesc);
                //旧逻辑没有修改审核任务表
                auditTaskService.auditTask(executionTaskModel, new SimpleSysUserInfo(user.getId(), user.getUserName()));
            }
        }
    }

    @Override
    public R deleteBatch(Integer[] ids, SysUserEntity user) {
        String result = this.deleteBatch(ids, user.getId());
        if (R.SUCCESS.equals(result)) {
            return R.ok().msg(commonLanguageProperties.getDeleteSuccess());
        } else {
            return R.fail(result);
        }
    }

    @Autowired
    public void setCommonLanguageProperties(CommonLanguageProperties commonLanguageProperties) {
        GlobalPictureUpdateServiceImpl.commonLanguageProperties = commonLanguageProperties;
    }


    /*************** ===私有方法=== ********************* ===start=== ***************************************/


    /**
     * 处理  添加
     *
     * @param list
     */
    private void addBatchPicture(List<GlobalPictureEntity> list, SysUserEntity user) {
        List<GlobalPictureEntity> savePicList = InstanceUtil.newArrayList(list.size());
        Date date = DateUtil.getCurDate();
        // 多张 图片
        for (GlobalPictureEntity picEntity : list) {
            PosterValidator.valid(picEntity);
            //保存前处理
            PosterSaveConverter.handleBeforeSave(picEntity);
            // 设置 创建人
            picEntity.setCreator(user.getId());
            // 设置创建时间
            picEntity.setCreatedDate(date);
            picEntity.setLastUpdateDate(date);
            savePicList.add(picEntity);
        }
        posterBiz.saveBatchAvoidEmpty(savePicList);
        handleSendMail(savePicList, user);
    }


    /**
     * 处理批量删除
     *
     * @param ids
     * @param userId
     * @return
     */
    private String deleteBatch(Integer[] ids, Integer userId) {
        if (ArrayUtils.isNotEmpty(ids)) {
            for (Integer pictureId : ids) {
                //检查图片是否被推荐位或主题使用
                if (posterBiz.isPosterHasUsed(pictureId)) {
                    return "The currently selected picture is " + commonLanguageProperties.getInUse() + commonLanguageProperties.getNotDelete();
                }
                GlobalPictureEntity globalPicture = posterBiz.queryById(pictureId);
                //判断板块是否已提交流程
                AuditTaskInfoEntity taskInfo = AuditUtil.getTaskByIdAndVersionAndType(globalPicture.getId(), null, ResourceTypeEnum.POSTER.getValue());
                if (taskInfo != null && taskInfo.getTaskFlag() == 1) {
                    return "[ID：" + pictureId + "][" + commonLanguageProperties.getName() + globalPicture.getPictureName() + "] the material has been submitted for review " + commonLanguageProperties.getNotDelete();
                }
            }
            //逻辑删除
            logicDelBatchByIds(ids);
        }
        return R.SUCCESS;
    }

    /**
     * 按id批量删除记录（逻辑删除）
     *
     * @param ids
     */
    private void logicDelBatchByIds(Integer[] ids) {
        UpdateTemplate<GlobalPictureEntity> wrapper = UpdateTemplate.getUpdateTemplate();
        wrapper.in("`id`", ids);
        GlobalPictureEntity update = new GlobalPictureEntity();
        update.setFlag(0);
        update.setLastUpdateDate(DateUtil.getCurDate());
        posterBiz.getMapper().update(update, wrapper);
    }


    /**
     * 处理发送邮件
     *
     * @param list
     * @param user
     */
    private void handleSendMail(List<GlobalPictureEntity> list, SysUserEntity user) {
        for (GlobalPictureEntity picEntity : list) {
            AuditUtil.openTask(picEntity.getPictureName(), picEntity.getId(), null, ResourceTypeEnum.POSTER.toString(), null,
                    user, 1);

        }
//        if (SystemProperties.SystemConstants.ENABLE_SEND_EMAIL) {
//            //发送邮件通知审核人
//            sendEmailService.sentEmailForPictureBatch(list, user);
//        }
    }
}
